package view 
{
	import flash.display.Sprite;
	import model.observer.IView;
	import model.Shapes.TetrisShape;
	import model.Utils;
	/**
	 * ...
	 * @author Yang Wang
	 */
	public class ShapeView extends Sprite implements IView
	{
		private var m_shape:TetrisShape;
		private var m_square:Square;
		
		public function ShapeView(shape:TetrisShape, square:Square = null) 
		{
			if (square == null) {
				square = new Square(shape.color);
			}
			m_shape = shape;			
			m_square = square;
			shape.addView(this);
			generateSprite();
		}
		
		public function get shape() : TetrisShape {
			return this.m_shape;
		}
		
		public function generateSprite() : void
		{	
			for (var orientation:int = 0; orientation < m_shape.NumStates; orientation++) {
				var sprite:Sprite = new Sprite();
				
				for (var i:int = 0; i < m_shape.getSquares(orientation).length; i++) {
					for (var j:int = 0; j < m_shape.getSquares(orientation)[i].length; j++) {
						if (m_shape.getSquares(orientation)[i][j]==true) {
							// TODO: should not generate new squares when rotating the shape
							var square:Square = this.createSquare();
							sprite.addChild(square);
							square.x = square.width * i;
							square.y = square.height * (m_shape.getSquares(orientation)[i].length-j-1);
						}
					}
				}
				this.addChild(sprite);
				
				if (orientation != m_shape.Orientation)
					this.getChildAt(this.getChildIndex(sprite)).visible = false;
			}
		}
		
		public function createSquare() : Square {
			return this.m_square.clone();
		}
		
		public function drawShape() : void 
		{
			for (var i:int = 0; i < m_shape.NumStates; i++)
				this.getChildAt(i).visible = false;
			
			this.getChildAt(m_shape.Orientation).visible = true;
		}
		
		/* INTERFACE model.observer.IView */
		
		public function updateView(obj:Object):void 
		{
			drawShape();
		}
		
		private function clearSprites() : void {
			while (numChildren > 0) {
				this.removeChildAt(0);
			}
		}
	}

}